package com.ruhaly.water.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.utils.ToastUtils;
import com.ruhaly.water.R;
import com.ruhaly.water.common.Constant;
import com.ruhaly.water.databinding.ActivityLoginBinding;
import com.ruhaly.water.manager.LogicManager;
import com.ruhaly.water.model.Server;
import com.ruhaly.water.model.User;
import com.ruhaly.common_lib.base.BaseActivity;
import com.ruhaly.common_lib.utils.JsonUtil;
import com.ruhaly.common_lib.utils.Utils;
import com.ruhaly.water.viewmodel.LoginViewModel;
import com.tbruyelle.rxpermissions.RxPermissions;

/**
 * Created by han_l on 2016/9/19.
 */
public class LoginActivity extends BaseActivity<ActivityLoginBinding> {

    LoginViewModel viewModel;
    RxPermissions rxPermissions;

    @Override
    public void initTitleFrame() {
        getB().titleFrame.tvTitle.setText("登录");
        getB().titleFrame.ivBack.setVisibility(View.GONE);
        getB().titleFrame.tvRight.setVisibility(View.VISIBLE);
        getB().titleFrame.tvRight.setText("");
        getB().titleFrame.tvRight.setBackgroundResource(R.mipmap.icon_setting);
        getB().titleFrame.tvRight.setOnClickListener(view -> {
            startActivity(new Intent(getBaseContext(), ServerSettingActivity.class));
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        initVM();
       /*以下控件设置*/
    }

    public void initVM() {
        viewModel = initVM(LoginViewModel.class);
        getB().setActivity(this);
        getB().setViewModel(viewModel);
        viewModel.setUser(JsonUtil.fromJson(Constant.getUserInfo(), User.class));

        rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.READ_PHONE_STATE)
                .subscribe(granted -> {
                    if (granted) { // 在android 6.0之前会默认返回true
                        viewModel.getUser().setPhone(Utils.getPhoneNum(getBaseContext()));
                    } else {
                        // 未获取权限
                        Utils.snack(LoginActivity.this, "读写权限被禁止,请在设置中打开授权");
                        Utils.openAppSetting(getBaseContext());
                    }
                });
    }

    public void login() {
        Server server = JsonUtil.fromJson(Constant.getServerInfo(), Server.class);
        if (null == server || TextUtils.isEmpty(server.getIp())) {
            ToastUtils.showShortToast("请先配置服务器地址");
            startActivity(new Intent(getBaseContext(), ServerSettingActivity.class));
            return;
        }

        if (TextUtils.isEmpty(viewModel.user.getUserName())) {
            getB().inputLayoutName.setErrorEnabled(true);
            getB().inputLayoutName.setError("用户名不能为空");
            getB().etPhone.requestFocus();
            return;
        }
        getB().inputLayoutName.setErrorEnabled(false);
        if (TextUtils.isEmpty(viewModel.user.getPwd())) {
            getB().inputLayoutPWD.setErrorEnabled(true);
            getB().inputLayoutPWD.setError("密码不能为空");
            getB().etPwd.requestFocus();
            return;
        }

        getB().inputLayoutPWD.setErrorEnabled(false);

        Constant.saveUserInfo(JsonUtil.toJson(viewModel.user));
        LogicManager.getInstance().login(viewModel.user)
                .compose(bindViewLifecycleTransformer(true))
                .subscribe(response -> {
                    viewModel.loginResponse = response.getData();
                    viewModel.user.setEmployeeId(viewModel.loginResponse.getEmployeeid());
                    Constant.saveUserInfo(JsonUtil.toJson(viewModel.user));

                    Intent intent = new Intent(this, MainActivity.class);
                    intent.putExtra("MENU", JsonUtil.toJson(viewModel.loginResponse));
                    startActivity(intent);
                    showProgress(false);
                    finish();
                }, throwable -> {
                    showProgress(false);
                    handleThrowable(throwable);
                });
    }

    public void logout() {
        LogicManager.getInstance().logout()
                .compose(bindViewLifecycleTransformer(true))
                .subscribe(loginResponse -> {
                    showProgress(false);
                    Utils.snack(this, "退出登陆成功");
                }, throwable -> {
                    showProgress(false);
                    handleThrowable(throwable);
                });
    }
}